<script setup>
import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
  Delete,
  Plus
} from '@element-plus/icons-vue'
import { onMounted, ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useConfigStore } from './stores/config'
import { useDark, useToggle } from '@vueuse/core'
import TempIcon from './components/TempIcon.vue'
import ShopIcon from './components/ShopIcon.vue'
import GoodIcon from './components/GoodIcon.vue'

let config = reactive({
  darkMode: false,
  formSize: '',
  tableSize: ''
})

const activeIndex = ref('0')
// 获取配置store
const configStore = useConfigStore()
let isDarkMode = ref(null)

watch(
  () => isDarkMode.value,
  (value) => {
    console.log('isDarkMode:', `默认：${value ? 'dark' : 'light'}`)
    if (value != null) {
      useDark({
        initialValue: value ? 'dark' : 'light',
        storageKey: null
      })
    }
  },
  { immediate: true },
  { deep: true }
)

// 存储cookie数据
const cookieData = ref(null)
// 存储淘宝数据
const tbData = ref(null)

// 配置弹窗可见性
const configDialogVisible = ref(false)
const proxyDialogVisible = ref(false)

// 代理配置
const proxyConfig = reactive({
  enabled: false,
  proxies: [{ ip: '', port: '' }]
})

const font = reactive({
  color: 'rgba(0, 0, 0, .15)'
})

// 获取当前主题状态
const getCurrentTheme = async () => {
  try {
    const result = await window.electronAPI.getCurrentTheme()
    if (result.success) {
      console.log('获取当前主题状态:', result.isDarkMode ? '深色模式' : '浅色模式')
      isDarkMode.value = result.isDarkMode
    } else {
      console.error('获取主题状态失败:', result.message)
      // 退回到系统主题检查
      checkCurrentTheme()
    }
  } catch (error) {
    console.error('获取主题状态时发生错误:', error)
    // 退回到系统主题检查
    checkCurrentTheme()
  }
}

onMounted(async () => {
  // 加载保存的配置
  await configStore.loadGlobalConfig()
  console.log('全局配置加载完成', configStore.globalConfig.darkMode)

  // 应用已保存的配置
  document.documentElement.dataset.size = configStore.getFormSize

  // 监听来自主进程的cookie数据
  if (window.api && window.api.onTbcookie) {
    window.api.onTbcookie((cookies) => {
      console.log('收到Cookie数据:', cookies)

      cookies.forEach((cookie) => {
        console.log(`${cookie.name}, ${cookie.value}`)
      })
      cookieData.value = cookies

      ElMessage({ message: '已获取Cookie数据', type: 'success' })
    })
  } else {
    alert('window.api is not available or onTbcookie is not defined')
    console.warn('window.api is not available or onTbcookie is not defined')
  }
  // 监听来自主进程的淘宝数据
  if (window.api && window.api.onTbdata) {
    window.api.onTbdata((data) => {
      console.log('收到淘宝数据:', data)
      tbData.value = data
      ElMessage({ message: '已获取淘宝数据', type: 'success' })

      // 刷新页面
      window.location.reload()
    })
  } else {
    console.warn('window.api is not available or onTbdata is not defined')
  }

  // 监听来自主进程的显示hello消息
  if (window.api && window.api.onShowHello) {
    window.api.onShowHello(() => {
      ElMessage({ message: 'Hello', type: 'success' })
    })
  } else {
    console.warn('window.api is not available or onShowHello is not defined')
  }

  // 监听来自主进程的设置消息
  if (window.api && window.api.onSetting) {
    window.api.onSetting(() => {
      configDialogVisible.value = true
      // 读取默认数据赋值
      config.darkMode = configStore.globalConfig.darkMode
      config.formSize = configStore.globalConfig.formSize
      config.tableSize = configStore.globalConfig.tableSize
    })
  } else {
    console.warn('window.api is not available or onSetting is not defined')
  }

  // 初始化时从主进程获取当前主题状态
  getCurrentTheme()

  // 监听主题变化
  window.api.onThemeChanged((event, isDarkMode) => {
    console.log('主题已更改为:', isDarkMode ? '深色' : '浅色')
    isDarkMode.value = isDarkMode
  })
})

const route = (path) => {
  window.electron.ipcRenderer.send('navigate', path)
}

// 保存配置
const saveConfig = async () => {
  // 保存表单大小配置
  document.documentElement.dataset.size = config.formSize

  // 保存暗黑模式设置
  const isDark = config.darkMode

  // 设置暗黑模式
  if (window.api && window.api.setDarkMode) {
    window.api.setDarkMode(isDark)
  } else {
    console.warn('window.api is not available or setDarkMode is not defined')
  }

  // 保存配置到Pinia store
  await configStore.setGlobalConfig(config)

  isDarkMode.value = isDark

  ElMessage({ message: '配置已保存', type: 'success' })
  configDialogVisible.value = false
}

// 检查当前主题
const checkCurrentTheme = () => {
  // 在渲染进程中检查系统主题偏好
  // 注意：这只是一个近似判断，准确的主题状态应该从主进程获取
  const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)').matches
  isDarkMode.value = prefersDarkScheme
}

// 代理设置相关函数
const openProxyDialog = () => {
  proxyDialogVisible.value = true
  loadProxyConfig()
}

// 加载代理配置
const loadProxyConfig = async () => {
  try {
    const { value } = await window.electronAPI.loadConfig('proxyConfig')
    console.log('加载代理配置:', value)
    if (value) {
      const config = JSON.parse(value)
      proxyConfig.enabled = config.enabled || false
      proxyConfig.proxies =
        config.proxies && config.proxies.length > 0 ? config.proxies : [{ ip: '', port: '' }]
    }
  } catch (error) {
    console.error('加载代理配置失败:', error)
    proxyConfig.proxies = [{ ip: '', port: '' }]
  }
}

// 添加代理输入框
const addProxy = () => {
  proxyConfig.proxies.push({ ip: '', port: '' })
}

// 删除代理输入框
const removeProxy = (index) => {
  if (proxyConfig.proxies.length > 1) {
    proxyConfig.proxies.splice(index, 1)
  }
}

// 保存代理配置
const saveProxyConfig = async () => {
  try {
    // 过滤掉空白的代理
    const validProxies = proxyConfig.proxies.filter((proxy) => proxy.ip && proxy.port)
    const configToSave = {
      enabled: proxyConfig.enabled,
      proxies: validProxies.length > 0 ? validProxies : [{ ip: '', port: '' }]
    }

    await window.electronAPI.saveConfig({
      key: 'proxyConfig',
      value: JSON.stringify(configToSave)
    })
    ElMessage({ message: '代理配置已保存', type: 'success' })
    proxyDialogVisible.value = false
  } catch (error) {
    console.error('保存代理配置失败:', error)
    ElMessage({ message: '保存代理配置失败', type: 'error' })
  }
}
</script>

<template>
  <el-config-provider :size="configStore.getFormSize">
    <div class="full-height">
      <el-container style="height: 100%">
        <el-header style="padding: 0px; height: 60px">
          <el-menu mode="horizontal" :default-active="activeIndex">
            <el-menu-item index="0" @click="route('/')">
              <img
                style="width: 100px"
                src="https://element-plus.org/images/element-plus-logo.svg"
                alt="Element logo"
              />
            </el-menu-item>
            <el-menu-item index="1" @click="route('/shop')">
              <el-icon><ShopIcon /></el-icon>
              <span>我的店铺</span>
            </el-menu-item>
            <el-menu-item index="2" @click="route('/temp')">
              <el-icon><TempIcon /></el-icon> <span>我的模板</span></el-menu-item
            >
            <el-menu-item index="3" @click="route('/goods')">
              <el-icon><GoodIcon /></el-icon> <span>发布商品</span></el-menu-item
            >
          </el-menu>
        </el-header>
        <el-main style="border-radius: 6px">
          <el-watermark :font="font" content="侵权必究">
            <el-scrollbar height="height: calc(100vh - 100px)">
              <router-view style="height: calc(100vh - 100px)" />
            </el-scrollbar>
          </el-watermark>
        </el-main>
      </el-container>
    </div>
  </el-config-provider>

  <!-- 系统配置弹窗 -->
  <el-dialog
    v-model="configDialogVisible"
    title="系统配置"
    width="400px"
    :before-close="() => (configDialogVisible = false)"
  >
    <el-form label-width="120px" :model="config">
      <!-- 暗黑模式切换 -->
      <el-form-item label="暗黑模式">
        <el-switch v-model="config.darkMode" />
      </el-form-item>

      <!-- 表单大小选择 -->
      <el-form-item label="表单按钮大小">
        <el-select v-model="config.formSize" placeholder="请选择表单大小">
          <el-option label="大" value="large" />
          <el-option label="默认" value="default" />
          <el-option label="小" value="small" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据表格大小">
        <el-select v-model="config.tableSize" placeholder="请选择表单大小">
          <el-option label="默认" value="medium" />
          <el-option label="小" value="small" />
          <el-option label="迷你" value="mini" />
        </el-select>
      </el-form-item>

      <!-- 代理设置按钮 -->
      <el-form-item label="代理设置">
        <el-button type="primary" :icon="Setting" @click="openProxyDialog" size="small">
          代理设置
        </el-button>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="configDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveConfig">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 代理设置弹窗 -->
  <el-dialog
    v-model="proxyDialogVisible"
    title="代理设置"
    width="500px"
    :before-close="() => (proxyDialogVisible = false)"
  >
    <el-form label-width="80px">
      <!-- 是否启用代理 -->
      <el-form-item label="启用代理">
        <el-switch v-model="proxyConfig.enabled" />
      </el-form-item>

      <!-- 代理列表 -->
      <div v-if="proxyConfig.enabled">
        <div v-for="(proxy, index) in proxyConfig.proxies" :key="index" class="proxy-item">
          <el-form-item :label="'代理' + (index + 1)">
            <div class="proxy-input-group">
              <el-input
                v-model="proxy.ip"
                placeholder="IP地址"
                style="width: 200px; margin-right: 10px"
              />
              <el-input
                v-model="proxy.port"
                placeholder="端口"
                style="width: 120px; margin-right: 10px"
              />
              <el-button
                type="danger"
                :icon="Delete"
                circle
                size="small"
                @click="removeProxy(index)"
                :disabled="proxyConfig.proxies.length === 1"
              />
            </div>
          </el-form-item>
        </div>

        <el-form-item label="">
          <el-button type="primary" :icon="Plus" @click="addProxy" size="small">
            添加代理
          </el-button>
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="proxyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProxyConfig">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.full-height {
  color: #fff;
  width: 100%;
  height: 100vh;
  min-height: 100vh;
}
el-header {
  padding: 0px !important;
}

.full-container {
  /* width: 100%;
  min-height: 100%;
  baground-color: #c0c0c0; */
}

.proxy-input-group {
  display: flex;
  align-items: center;
}

.proxy-item {
  margin-bottom: 10px;
}
</style>
